package tt.dz.biz.service.rpc;

import com.alibaba.fastjson.JSONObject;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.avro.Protocol;
import org.apache.avro.Protocol.Message;
import org.apache.avro.generic.GenericRecord;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import tt.dz.biz.dao.user.UserDAOImpl;
import tt.dz.biz.service.thirdaccount.ThirdAccountService;
import tt.dz.common.BusinessException;
import tt.dz.common.DzConstants;
import tt.dz.common.DzConstants.Common;
import tt.dz.common.DzErrorCode;
import tt.dz.common.DzErrorCode.CommonErrorCode;
import tt.dz.common.DzErrorCode.ExceptionErrorCode;
import tt.dz.common.DzErrorCode.ThirdAccountErrorCode;
import tt.dz.common.DzErrorCode.UserErrorCode;
import tt.dz.common.RPCUtil;
import tt.dz.vo.ThirdAccountVo;
import tt.dz.vo.UserBaseVO;
import tt.dz.vo.request.BaseRpcRequestVo;
import tt.dz.vo.request.BindThirdAccountRpcRequestVo;
import tt.dz.vo.request.ExitThirdAccountBindRpcRequestVo;
import tt.dz.vo.request.IsBindThirdAccountRpcRequestVo;
import tt.dz.vo.request.OffBindThirdAccountRpcRequestVo;
import tt.dz.vo.request.QueryBindThirdAccountRpcRequestVo;

@Service("rpcThirdAccountService")
public class RPCThirdAccountService
  implements RPCBaseService
{
  public static final String IS_BIND_THIRD_ACCOUN = "isBindThirdAccount";
  public static final String BIND_THIRD_ACCOUNT = "bindThirdAccount";
  public static final String OFF_BIND_THIRD_ACCOUNT = "offBindThirdAccount";
  public static final String QUERY_BIND_THIRD_ACCOUNT = "queryBindThirdAccount";
  public static final String EXIST_THIRD_ACCOUNT_BIND = "existThirdAccountBind";
  @Autowired
  @Qualifier("thirdAccountService")
  private ThirdAccountService thirdAccountService;
  @Autowired
  @Qualifier("userDAO")
  private UserDAOImpl userDAO;
  
  public Object execute(Protocol.Message message, Object request, Protocol protocol)
    throws Exception
  {
    String method = message.getName();
    Object result = null;
    Object req = ((GenericRecord)request).get("req");
    String requestStr = req.toString();
    if ("isBindThirdAccount".equals(method)) {
      result = isBindThirdAccount(requestStr);
    } else if ("bindThirdAccount".equals(method)) {
      result = bindThirdAccount(requestStr);
    } else if ("offBindThirdAccount".equals(method)) {
      result = offBindThirdAccount(requestStr);
    } else if ("queryBindThirdAccount".equals(method)) {
      result = queryBindThirdAccount(requestStr);
    } else if ("existThirdAccountBind".equals(method)) {
      result = existThirdAccountBind(requestStr);
    }
    if (result == null) {
      result = RPCUtil.generateResponseObject(Integer.valueOf(0), DzErrorCode.ExceptionErrorCode.COMMON_EXCEPTION.value(), DzErrorCode.ExceptionErrorCode.COMMON_EXCEPTION.getDesc());
    }
    return result.toString();
  }
  
  private Object existThirdAccountBind(String requestStr)
  {
    JSONObject resultJson = null;
    int exist = 0;
    try
    {
      ExitThirdAccountBindRpcRequestVo vo = (ExitThirdAccountBindRpcRequestVo)BaseRpcRequestVo.convertAndValidateVo(requestStr, ExitThirdAccountBindRpcRequestVo.class);
      String bindType = vo.getBindType();
      String thirdUuuid = vo.getThirdUuuid();
      String merchantCode = vo.getMerchantCode();
      List<ThirdAccountVo> thirdAccounts = this.thirdAccountService.queryThirdAccuntByBindTypeAndThirdUuuidAndMerchantCode(bindType, thirdUuuid, merchantCode);
      resultJson = RPCUtil.generateResponseObject(Integer.valueOf(1), "", "");
      if ((thirdAccounts != null) && (!thirdAccounts.isEmpty()))
      {
        exist = DzConstants.Common.ONE.intValue();
        resultJson.put("result", thirdAccounts);
      }
    }
    catch (BusinessException e)
    {
      resultJson = RPCUtil.generateResponseObject(Integer.valueOf(0), e.getStatusCode(), e.getStatusDescribe());
    }
    catch (Exception e)
    {
      resultJson = RPCUtil.generateResponseObject(Integer.valueOf(0), DzErrorCode.ExceptionErrorCode.COMMON_EXCEPTION.value(), DzErrorCode.ExceptionErrorCode.COMMON_EXCEPTION.getDesc());
    }
    resultJson.put("isExist", Integer.valueOf(exist));
    return resultJson;
  }
  
  private Object queryBindThirdAccount(String requestStr)
  {
    JSONObject resultJson = null;
    try
    {
      QueryBindThirdAccountRpcRequestVo vo = (QueryBindThirdAccountRpcRequestVo)BaseRpcRequestVo.convertAndValidateVo(requestStr, QueryBindThirdAccountRpcRequestVo.class);
      
      String userId = validateAndCheckUserId(vo.getTokenKey(), vo.getTokenKey(), vo.getMerchantCode());
      String bindType = vo.getBindType();
      
      List<ThirdAccountVo> thirdAccounts = null;
      if (!StringUtils.isEmpty(bindType)) {
        thirdAccounts = this.thirdAccountService.queryThirdAccoutByUserIdAndBindType(userId, bindType);
      } else {
        thirdAccounts = this.thirdAccountService.queryThirdAccoutByUserId(userId);
      }
      if ((thirdAccounts == null) || (thirdAccounts.isEmpty()))
      {
        resultJson = RPCUtil.generateResponseObject(Integer.valueOf(0), DzErrorCode.ThirdAccountErrorCode.NOT_EXITS.value(), DzErrorCode.ThirdAccountErrorCode.NOT_EXITS.getDesc());
      }
      else
      {
        resultJson = RPCUtil.generateResponseObject(Integer.valueOf(1), "", "");
        resultJson.put("result", thirdAccounts);
      }
    }
    catch (BusinessException e)
    {
      resultJson = RPCUtil.generateResponseObject(Integer.valueOf(0), e.getStatusCode(), e.getStatusDescribe());
    }
    catch (Exception e)
    {
      resultJson = RPCUtil.generateResponseObject(Integer.valueOf(0), DzErrorCode.ExceptionErrorCode.COMMON_EXCEPTION.value(), DzErrorCode.ExceptionErrorCode.COMMON_EXCEPTION.getDesc());
    }
    return resultJson;
  }
  
  private Object offBindThirdAccount(String requestStr)
  {
    JSONObject resultJson = null;
    try
    {
      OffBindThirdAccountRpcRequestVo vo = (OffBindThirdAccountRpcRequestVo)BaseRpcRequestVo.convertAndValidateVo(requestStr, OffBindThirdAccountRpcRequestVo.class);
      
      String userId = validateAndCheckUserId(vo.getTokenKey(), vo.getTokenKey(), vo.getMerchantCode());
      String bindType = vo.getBindType();
      String thirdUuuid = vo.getThirdUuuid();
      
      List<ThirdAccountVo> deleteThirdAccounts = new ArrayList();
      if (!StringUtils.isEmpty(thirdUuuid))
      {
        ThirdAccountVo thirdAccountVo = this.thirdAccountService.queryThirdAccountByUserIdAndBindTypeAndThirdUUid(userId, bindType, thirdUuuid);
        if (thirdAccountVo != null) {
          deleteThirdAccounts.add(thirdAccountVo);
        }
      }
      else
      {
        deleteThirdAccounts = this.thirdAccountService.queryThirdAccoutByUserIdAndBindType(userId, bindType);
      }
      if ((deleteThirdAccounts == null) || (deleteThirdAccounts.isEmpty())) {
        return RPCUtil.generateResponseObject(Integer.valueOf(0), DzErrorCode.ThirdAccountErrorCode.NOT_EXITS.value(), DzErrorCode.ThirdAccountErrorCode.NOT_EXITS.getDesc());
      }
      this.thirdAccountService.deteleAccounts((ThirdAccountVo[])deleteThirdAccounts.toArray(new ThirdAccountVo[deleteThirdAccounts.size()]));
      int isSuccess = 1;
      return RPCUtil.generateResponseObject(Integer.valueOf(isSuccess), "", "");
    }
    catch (BusinessException e)
    {
      resultJson = RPCUtil.generateResponseObject(Integer.valueOf(0), e.getStatusCode(), e.getStatusDescribe());
    }
    catch (Exception e)
    {
      resultJson = RPCUtil.generateResponseObject(Integer.valueOf(0), DzErrorCode.ExceptionErrorCode.COMMON_EXCEPTION.value(), DzErrorCode.ExceptionErrorCode.COMMON_EXCEPTION.getDesc());
    }
    return resultJson;
  }
  
  private Object bindThirdAccount(String requestStr)
  {
    JSONObject resultJson = null;
    try
    {
      BindThirdAccountRpcRequestVo vo = (BindThirdAccountRpcRequestVo)BaseRpcRequestVo.convertAndValidateVo(requestStr, BindThirdAccountRpcRequestVo.class);
      String bindType = vo.getBindType();
      String thirdUuuid = vo.getThirdUuuid();
      
      int count = this.thirdAccountService.queryThirdAccuntByBindTypeAndThirdUuuidAndMerchantCodeCount(bindType, thirdUuuid, vo.getMerchantCode());
      if (count > 0) {
        return RPCUtil.generateResponseObject(Integer.valueOf(0), DzErrorCode.ThirdAccountErrorCode.QUERY_MULTI_BIND.value(), DzErrorCode.ThirdAccountErrorCode.QUERY_MULTI_BIND.getDesc());
      }
      String userId = validateAndCheckUserId(vo.getTokenKey(), vo.getTokenKey(), vo.getMerchantCode());
      
      ThirdAccountVo thirdAccountVo = this.thirdAccountService.queryThirdAccountByUserIdAndBindTypeAndThirdUUid(userId, bindType, thirdUuuid);
      if (thirdAccountVo != null) {
        return RPCUtil.generateResponseObject(Integer.valueOf(0), DzErrorCode.ThirdAccountErrorCode.REPEAT_BIND.value(), DzErrorCode.ThirdAccountErrorCode.REPEAT_BIND.getDesc());
      }
      boolean isPrimaryKeyExist = this.thirdAccountService.isExistUUUIDUserIdRepeat(userId, thirdUuuid);
      if (isPrimaryKeyExist) {
        return RPCUtil.generateResponseObject(Integer.valueOf(0), DzErrorCode.CommonErrorCode.PRIMARY_KEY_REPEAT.value(), DzErrorCode.CommonErrorCode.PRIMARY_KEY_REPEAT.getDesc());
      }
      thirdAccountVo = new ThirdAccountVo();
      thirdAccountVo.setUserId(userId);
      thirdAccountVo.setThirdUuuid(thirdUuuid);
      thirdAccountVo.setBindType(bindType);
      thirdAccountVo.setBindTime(new Date());
      thirdAccountVo.setIsValidate(DzConstants.Common.ONE.intValue());
      boolean isInsertSave = this.thirdAccountService.save(thirdAccountVo);
      int isSuccess = isInsertSave ? 1 : 0;
      return RPCUtil.generateResponseObject(Integer.valueOf(isSuccess), "", "");
    }
    catch (BusinessException e)
    {
      resultJson = RPCUtil.generateResponseObject(Integer.valueOf(0), e.getStatusCode(), e.getStatusDescribe());
    }
    catch (Exception e)
    {
      resultJson = RPCUtil.generateResponseObject(Integer.valueOf(0), DzErrorCode.ExceptionErrorCode.COMMON_EXCEPTION.value(), DzErrorCode.ExceptionErrorCode.COMMON_EXCEPTION.getDesc());
    }
    return resultJson;
  }
  
  private Object isBindThirdAccount(String requestStr)
  {
    JSONObject resultJson = null;
    try
    {
      IsBindThirdAccountRpcRequestVo vo = (IsBindThirdAccountRpcRequestVo)BaseRpcRequestVo.convertAndValidateVo(requestStr, IsBindThirdAccountRpcRequestVo.class);
      
      String userId = validateAndCheckUserId(vo.getTokenKey(), vo.getTokenKey(), vo.getMerchantCode());
      String bindType = vo.getBindType();
      String thirdUuuid = vo.getThirdUuuid();
      ThirdAccountVo thirdAccountVo = this.thirdAccountService.queryThirdAccountByUserIdAndBindTypeAndThirdUUid(userId, bindType, thirdUuuid);
      
      int isSuccess = (thirdAccountVo != null) && (thirdAccountVo.getIsValidate() == DzConstants.Common.ONE.intValue()) ? 1 : 0;
      return RPCUtil.generateResponseObject(Integer.valueOf(isSuccess), "", "");
    }
    catch (BusinessException e)
    {
      resultJson = RPCUtil.generateResponseObject(Integer.valueOf(0), e.getStatusCode(), e.getStatusDescribe());
    }
    catch (Exception e)
    {
      resultJson = RPCUtil.generateResponseObject(Integer.valueOf(0), DzErrorCode.ExceptionErrorCode.COMMON_EXCEPTION.value(), DzErrorCode.ExceptionErrorCode.COMMON_EXCEPTION.getDesc());
    }
    return resultJson;
  }
  
  private String validateAndCheckUserId(String userId, String mobileNo, String merchanatCode)
  {
    UserBaseVO userBaseVO = this.userDAO.getUserBaseByUserId(userId, null, merchanatCode);
    userBaseVO = userBaseVO == null ? this.userDAO.getUserBaseByUserId(null, mobileNo, merchanatCode) : userBaseVO;
    if (userBaseVO == null) {
      throw new BusinessException(DzErrorCode.UserErrorCode.USER_NOT_FOUND.value(), DzErrorCode.UserErrorCode.USER_NOT_FOUND.getDesc());
    }
    return userBaseVO.getUserId();
  }
}
